package com.fdb.efp.console.api.rest;

import com.irdstudio.basic.framework.core.bean.KeyValue;
import com.irdstudio.basic.framework.core.constant.*;
import com.irdstudio.basic.framework.core.vo.EngineHttpRequestVO;
import com.irdstudio.basic.framework.core.vo.UserInfo;
import com.irdstudio.basic.framework.web.controller.AbstractController;
import com.irdstudio.basic.framework.web.util.HttpClientUtil;
import com.irdstudio.basic.sequence.service.DefaultPatternDescriptor;
import com.irdstudio.basic.sequence.service.PatternDescriptor;
import com.irdstudio.basic.sequence.service.facade.PatternedLimitableSeqService;
import com.irdstudio.efp.console.common.ConsoleConstant;
import com.irdstudio.efp.console.service.facade.*;
import com.irdstudio.efp.console.service.vo.PrdCaseManageVO;
import com.irdstudio.efp.console.service.vo.PrdInfoVO;
import com.irdstudio.efp.console.service.vo.RateSchemeCfgVO;
import com.irdstudio.efp.console.service.vo.RateSchemeDetailVO;
import com.irdstudio.efp.e4a.service.facade.SRoleDataRuleService;
import com.irdstudio.efp.flow.service.facade.BizFlowInfoService;
//import com.irdstudio.efp.flow.service.facade.FlowUrlConfigService;
import com.irdstudio.efp.flow.service.vo.BizFlowInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.irdstudio.basic.sequence.service.DefaultPatternDescriptor.SEQ;

@RestController
@RequestMapping("/api")
public class PrdCaseManageController extends AbstractController {

	public static final PatternDescriptor PATTERN = DefaultPatternDescriptor.of(SEQ, 5);
	
	@Autowired
	@Qualifier("prdCaseManageService")
	private PrdCaseManageService prdCaseManageService;
	@Autowired
	private PatternedLimitableSeqService sequenceService;
	@Autowired
	@Qualifier("prdInfoService")
	private PrdInfoService prdInfoService;
//	@Autowired
//	@Qualifier("flowUrlConfigService")
//	private FlowUrlConfigService flowUrlConfigService;
	@Autowired
	@Qualifier("bizFlowInfoService")
	private BizFlowInfoService bizFlowInfoService;
	@Autowired
	@Qualifier("rateSchemeCfgService")
	private RateSchemeCfgService rateSchemeCfgService;
	@Autowired
	@Qualifier("rateSchemeDetailService")
	private RateSchemeDetailService rateSchemeDetailService;
	@Autowired
	@Qualifier("sRoleDataRuleService")
	private SRoleDataRuleService sRoleDataRuleService;

	/**
	 * 列表数据查询
	 * 
	 * @param page
	 * @param size
	 * @return
	 */
	@RequestMapping(value = "/prd/case/manages", method = RequestMethod.POST)
	public @ResponseBody ResponseData<List<PrdCaseManageVO>> queryPrdCaseManageAll(@RequestBody PrdCaseManageVO vo) {
		// 根据用户角色获取用户权限方案
		List<PrdCaseManageVO> outputVo = null;
		Map<String,String> dataRuleTypeMap = sRoleDataRuleService.getDataRuleType(httpRequest.getRequestURI(), getUserRoles());
		vo.setPrdCodebyBaseInfo(dataRuleTypeMap == null ? null:dataRuleTypeMap.get(PubConstant.PRD_CODE));
		DataRuleType dataRuleType = DataRuleType.getDataRuleType(dataRuleTypeMap == null ? null:dataRuleTypeMap.get(PubConstant.PERMIS_TYPE));
		setUserInfoToVO(vo);
		// 根据权限方案调用不同的方案进行数据查询
		switch (dataRuleType) {
		case Owner:
			outputVo = prdCaseManageService.queryAllOwner(vo);
			break;
		case CurrOrg:
			outputVo = prdCaseManageService.queryAllCurrOrg(vo);
			break;
		case CurrDownOrg:
			outputVo = prdCaseManageService.queryAllCurrDownOrg(vo);
			break;
		default:
			outputVo = prdCaseManageService.queryAllOwner(vo);
			break;
		}
		this.displayNames(outputVo, new KeyValue("createUser", "createUserName"), new KeyValue("legalOrgCode", "legalOrgCodeName"));
		return getResponseData(outputVo);
	}

	/**
	 * 根据主键查询详情
	 * 
	 * @return
	 */
	@RequestMapping(value = "/prd/case/manage/{caseCode}", method = RequestMethod.GET)
	public @ResponseBody ResponseData<PrdCaseManageVO> queryByPk(@PathVariable("caseCode") String caseCode) {
		PrdCaseManageVO inVo = new PrdCaseManageVO();
		inVo.setCaseCode(caseCode);
		PrdCaseManageVO outputVo = prdCaseManageService.queryByPk(inVo);
		return getResponseData(outputVo);

	}

	/**
	 * 根据主键删除信息
	 * 
	 * @param prdCaseManage
	 * @return
	 */
	@RequestMapping(value = "/prd/case/manage", method = RequestMethod.DELETE)
	public @ResponseBody ResponseData<Integer> deleteByPk(@RequestBody PrdCaseManageVO inPrdCaseManageVo) {
		int outputVo = prdCaseManageService.deleteByPk(inPrdCaseManageVo);
		return getResponseData(outputVo);

	}

	/**
	 * 根据主键更新信息
	 * 
	 * @param inPrdCaseManageVo
	 * @return
	 */
	@RequestMapping(value = "/prd/case/manage", method = RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> updateByPk(@RequestBody PrdCaseManageVO inPrdCaseManageVo) {
		int outputVo = prdCaseManageService.updateByPk(inPrdCaseManageVo);
		return getResponseData(outputVo);

	}

	/**
	 * 新增数据
	 * 
	 * @param inPrdCaseManageVo
	 * @return
	 */
	@RequestMapping(value = "/prd/case/manage", method = RequestMethod.POST)
	public @ResponseBody ResponseData<Integer> insertPrdCaseManage(@RequestBody PrdCaseManageVO inPrdCaseManageVo) {
		int outputVo = -1;
		// 获取流水号
		String caseCode = "";
		try {
			caseCode = sequenceService.getPatternedSequence("CASE_CODE", PATTERN);
		} catch (Exception e) {
			logger.debug("获取流水号失败!");
			return getResponseData(outputVo);
		}
		setUserInfoToVO(inPrdCaseManageVo);
		inPrdCaseManageVo.setCaseCode(caseCode);// 流水号
		inPrdCaseManageVo.setAprvStatus(ConsoleConstant.APRV_STATUS_01);// 待发起
		inPrdCaseManageVo.setCaseStatus(ConsoleConstant.CASE_STATUS_01);// 待生效
		outputVo = prdCaseManageService.insertPrdCaseManage(inPrdCaseManageVo);
		return getResponseData(outputVo);

	}

	/**
	 * 提交处理
	 * 
	 * @param inPrdCaseManageVo
	 * @return
	 */
//	@RequestMapping(value = "/prd/case/submitManage", method = RequestMethod.POST)
//	public @ResponseBody ResponseData<Integer> submitPrdCaseManage(@RequestBody PrdCaseManageVO inPrdCaseManageVo) {
//		int count = -1;
//		String caseCode = "";
//		if (Objects.nonNull(inPrdCaseManageVo)) {
//			try {
//				caseCode = inPrdCaseManageVo.getCaseCode();
//				String prdId = inPrdCaseManageVo.getPrdId();
//				PrdInfoVO prdVo = new PrdInfoVO();
//				prdVo.setPrdId(prdId);
//				prdVo = prdInfoService.queryByPk(prdVo);
//				if (prdVo != null && !ConsoleConstant.PRD_STATUS_02.equals(prdVo.getPrdStatus())) {
//					ResponseData<Integer> responseData = new ResponseData<Integer>();
//					responseData.setMessage("该产品为非生效状态");
//					responseData.setCode(ApplicationConstance.FAILURE);
//					responseData.setSuccess(false);
//					return responseData;
//				}
//				// 校验同一时间内只能有一条生效数据,否则不能提交
//				List<PrdCaseManageVO> prdCaseManages = prdCaseManageService.queryPrdCaseManageByPrdCodeTime(inPrdCaseManageVo);
//				if (prdCaseManages != null && prdCaseManages.size() > 0) {
//					ResponseData<Integer> responseData = new ResponseData<Integer>();
//					responseData.setMessage("同一产品只允许存在一条专案！");
//					responseData.setCode(ApplicationConstance.FAILURE);
//					responseData.setSuccess(false);
//					return responseData;
//				}
//				// 提交时校验选择的利率方案
//				ResponseData<Integer> response = check(inPrdCaseManageVo);
//				if (Objects.nonNull(response)) {
//					return response;
//				}
//				String flowId = "";
//				UserInfo userInfo = getUserInfo();
//				String legalOrgCode = userInfo.getLegalOrg().getOrgCode();
//				BizFlowInfoVO bizFlowInfoVo = new BizFlowInfoVO();
//				bizFlowInfoVo.setLegalOrgCode(legalOrgCode);
//				bizFlowInfoVo.setBizFlowType(BaseConstant.BIZ_FLOW_TYPE_01);
//				List<BizFlowInfoVO> list = bizFlowInfoService.queryBizFlowInfoByFlowType(bizFlowInfoVo);
//				if (Objects.nonNull(list) && list.size() > 0) {
//					bizFlowInfoVo = list.get(0);
//					flowId = bizFlowInfoVo.getBizFlowId();
//				} else {
//					// 若没有该法人机构配置则走省配置
//					bizFlowInfoVo.setLegalOrgCode(BaseConstant.LEGAL_ORG_CODE_00001);
//					list = bizFlowInfoService.queryBizFlowInfoByFlowType(bizFlowInfoVo);
//					if (Objects.nonNull(list) && list.size() > 0) {
//						bizFlowInfoVo = list.get(0);
//						flowId = bizFlowInfoVo.getBizFlowId();
//					} else {
//						ResponseData<Integer> responseData = new ResponseData<Integer>();
//						responseData.setMessage("该法人机构未配置专案业务流转，提交失效！");
//						responseData.setCode(ApplicationConstance.FAILURE);
//						responseData.setSuccess(false);
//						return responseData;
//					}
//				}
//				inPrdCaseManageVo.setAprvStatus(ConsoleConstant.APRV_STATUS_01);// 待发起
//				inPrdCaseManageVo.setCaseStatus(ConsoleConstant.CASE_STATUS_01);// 待生效
//				// 有流水号则更新数据，没有则新增数据
//				if (caseCode != null && !"".equals(caseCode)) {
//					// 修改申请
//					count = prdCaseManageService.updateByPk(inPrdCaseManageVo);
//				} else {
//					try {
//						// 获取流水号
//						caseCode = sequenceService.getPatternedSequence("CASE_CODE", PATTERN);
//					} catch (Exception e) {
//						logger.debug("获取流水号失败!");
//						return getResponseData(count);
//					}
//					inPrdCaseManageVo.setCaseCode(caseCode);// 流水号
//					setUserInfoToVO(inPrdCaseManageVo);
//					// 插入申请表
//					count = prdCaseManageService.insertPrdCaseManage(inPrdCaseManageVo);
//				}
//
//				String eventId = "E000010";
//				try {
//					EngineHttpRequestVO eVo = new EngineHttpRequestVO();
//					eVo.setBizLagelOrgCode(inPrdCaseManageVo.getOrgCode());
//					eVo.setE_bizSerno(inPrdCaseManageVo.getCaseCode());
//					eVo.setFlowId(flowId);
//					eVo.setEventId(eventId);
//					eVo.setG_bizSerno(inPrdCaseManageVo.getPrdCode());
//					eVo.setData(inPrdCaseManageVo);
//					HttpClientUtil.callFlowEngine(flowUrlConfigService.getRestfulSyncStartEventUrl(), eVo, String.class);
//				} catch (Exception e) {
//					logger.error("发生异常!", e);
//					ResponseData<Integer> responseData = new ResponseData<Integer>();
//					responseData.setMessage("保存成功，调用流程异常，提交失败！");
//					responseData.setCode("-2");
//					responseData.setSuccess(false);
//					return responseData;
//				}
//				inPrdCaseManageVo.setAprvStatus(ConsoleConstant.APRV_STATUS_02);// 审批中
//				// inPrdCaseManageVo.setAprvStatus(ConsoleConstant.APRV_STATUS_03);//通过
//				// 更新申请表
//				count = prdCaseManageService.updateByPk(inPrdCaseManageVo);
//			} catch (Exception e) {
//				logger.error("发生异常!", e);
//			}
//
//		}
//		return getResponseData(count);
//	}

	/**
	 * 提交时校验利率方案是否生效等
	 * 
	 * @param inPrdInfoApplyVo
	 * @return
	 */
	private ResponseData<Integer> check(PrdCaseManageVO inPrdCaseManageVo) {
		ResponseData<Integer> responseData = null;
		// 校验产品选择的利率方案
		String schemeNo = inPrdCaseManageVo.getRateSchemeId();
		if (schemeNo != null && !"".equals(schemeNo)) {
			RateSchemeCfgVO rateSchemeCfgVO = new RateSchemeCfgVO();
			rateSchemeCfgVO.setSchemeNo(schemeNo);
			rateSchemeCfgVO = rateSchemeCfgService.queryByPk(rateSchemeCfgVO);
			String prdId = inPrdCaseManageVo.getPrdId();
			PrdInfoVO prdInfoVo = new PrdInfoVO();
			prdInfoVo.setPrdId(prdId);
			// 查询产品信息
			prdInfoVo = prdInfoService.queryByPk(prdInfoVo);
			if (Objects.isNull(rateSchemeCfgVO) || (Objects.nonNull(rateSchemeCfgVO) && rateSchemeCfgVO.getStatus() != null
					&& !ConsoleConstant.COMMON_STATUS_1.equals(rateSchemeCfgVO.getStatus()))) {
				responseData = new ResponseData<Integer>();
				responseData.setMessage("利率方案状态为非生效！");
				responseData.setCode(ApplicationConstance.FAILURE);
				responseData.setSuccess(false);
				return responseData;
			} else if (rateSchemeCfgVO != null && !prdInfoVo.getCreditTermUnit().equals(rateSchemeCfgVO.getSingleTermUnit())) {
				responseData = new ResponseData<Integer>();
				responseData.setMessage("产品期限单位与利率方案期限单位不匹配！");
				responseData.setCode(ApplicationConstance.FAILURE);
				responseData.setSuccess(false);
				return responseData;
			}
			RateSchemeDetailVO rsdVO = new RateSchemeDetailVO();
			rsdVO.setSchemeNo(schemeNo);
			rsdVO.setTerm(prdInfoVo.getCreditTerm() + "");
			rsdVO = rateSchemeDetailService.queryByschemeNoTerm(rsdVO);
			if (rsdVO == null) {
				responseData = new ResponseData<Integer>();
				responseData.setMessage("产品期限与利率方案配置不匹配！" + prdInfoVo.getCreditTerm());
				responseData.setCode(ApplicationConstance.FAILURE);
				responseData.setSuccess(false);
				return responseData;
			}
		}
		return null;
	}

	/**
	 * 专案停用
	 * 
	 * @param inPrdCaseManageVo
	 * @return
	 */
	@RequestMapping(value = "/prd/case/stopCase", method = RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> stopPrdInfo(@RequestBody PrdCaseManageVO inPrdCaseManageVo) {
		// 更新专案状态为已停用
		inPrdCaseManageVo.setCaseStatus(ConsoleConstant.CASE_STATUS_03);// 已停用
		int outputVo = prdCaseManageService.updateByPk(inPrdCaseManageVo);
		return getResponseData(outputVo);
	}
}
